
import requests
import logging

logger = logging.getLogger("requests.session")
logging.basicConfig(level=logging.INFO)

class RequestsSession(requests.Session):
    def __init__(self,base_url=""):
        self.base_url = base_url
        super().__init__()

    # 重写request方法
    def request(self,method,url,*args,**kwargs):
        if not url.startswith('http'):
            url = self.base_url + url
        return super().request(method,url,*args,**kwargs)

    # 重写send方法，记录日志
    def send(self,request: requests.PreparedRequest,*args,**kwargs):
        logger.info(f"发送请求>>>>>> 接口地址={request.method} {request.url}")
        logger.info(f"发送请求>>>>>> 请求头={request.headers} ")
        logger.info(f"发送请求>>>>>> 请求体={request.body} ")

        response = super().send(request,*args,**kwargs)
        logger.info(f"接收响应>>>>>> 状态码={response.status_code}")
        logger.info(f"接收响应>>>>>> 响应头={response.headers} ")
        logger.info(f"接收响应>>>>>> 响应体={response.content} ")
        return response

if __name__ == '__main__':
    data={"password": "sdfsdf","username": "byhy"}
    session = RequestsSession("http://localhost:8234/api")
    rep = session.request(
        'get','/operator/devicetype/list')
    print(rep)